package me.zhengjie.modules.business.service.impl;

import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.business.service.FileService;
import me.zhengjie.modules.business.util.ImageUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * class description：
 *
 * @author rsw
 * Date: 2020/2/5
 * Time: 14:26
 **/
@Service
public class FileServiceImpl implements FileService {

    /**
     * 配置文件上传路径
     */
    @Value("${file.path}")
    private String filePath;

    /**
     * 配置问题图片上传路径
     */
    @Value("${file.question}")
    private String questionPath;

    /** 配置文件压缩比例 */
    @Value("${file.scale}")
    private double scale;

    /** 配置文件压缩比例 */
    @Value("${file.scaleWith}")
    private double scaleWith;

    /** 配置文件压缩比例 */
    @Value("${file.scaleHeight}")
    private double scaleHeight;

    @Override
    public String upload(MultipartFile multipartFile) {
        File file = me.zhengjie.utils.FileUtil.upload(multipartFile, filePath);
        if (file == null) {
            throw new BadRequestException("文件上传失败");
        }
        //返回图片地址
        return "file/" + file.getName();
    }

    @Override
    public Map<String,String> uploadImage(MultipartFile multipartFile) {
        String[] imageTypeArr = {"jpg", "png"};
        //如果文件是图片类型
        if (ImageUtil.verifyImageFile(multipartFile)) {
            //上传图片
            File file = me.zhengjie.utils.FileUtil.upload(multipartFile, questionPath);
            if (file == null) {
                throw new BadRequestException("文件上传失败");
            }
            //压缩文件上传
            String[] split = file.getName().split("\\.");
            split[0]+="_thum";
            String thumFileName = split[0]+"."+split[1];
            ImageUtil.imageScaleUpload(file.getPath(),scale,questionPath+thumFileName);
            //返回图片名
            Map<String,String> result=new HashMap<>();
            result.put("picturePath","question/" + file.getName());
            result.put("thumbnailPath","question/" +thumFileName);
            return result;
        } else {
            throw new BadRequestException("请上传图片类型的文件");
        }
    }

}

